<template>
  <div>
    <a-input-search v-model="names" readOnly unselectable="on" @search="onSearch">
      <a-button
        @click.native="visible = true"
        slot="enterButton"
        :disabled="disabled"
        :icon="searchIcon ? 'search' : ''"
        >{{ searchIcon ? '' : searchBtnText || '选择用户' }}</a-button
      >
    </a-input-search>

    <!-- 查询窗口 -->
    <a-modal
      :width="modalWidth"
      :visible="visible"
      :title="'选择' + title"
      @ok="handleSelected"
      @cancel="close"
      style="top:50px"
      cancelText="关闭"
    >
      <a-form
        style="margin-bottom:20px;"
        layout="inline"
        @keyup.enter.native="search"
        v-if="searchType != 'deptInRole'"
      >
        <!-- user -->
        <a-row :gutter="48">
          <template v-if="searchType == 'user'">
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.username" placeholder="输入学工号" />
            </a-col>
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.realname" placeholder="输入姓名" />
            </a-col>
          </template>
          <template v-if="searchType == 'role'">
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.roleName" placeholder="输入角色名称" />
            </a-col>
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.roleCode" placeholder="输入角色编码" />
            </a-col>
          </template>
          <template v-if="searchType == 'dept'">
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.keyWord" placeholder="输入部门名称" />
            </a-col>
          </template>
          <template v-if="searchType == 'post'">
            <a-col :md="6" :sm="8">
              <a-input placeholder="请输入职务编码" v-model="queryParam.code"></a-input>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-input placeholder="请输入职务名称" v-model="queryParam.name"></a-input>
            </a-col>
          </template>
          <template v-if="searchType == 'deptInPost'">
            <a-col :md="6" :sm="24">
              <a-select v-model="queryParam.category" placeholder="部门类型">
                <a-select-option value="org_society">社团</a-select-option>
                <a-select-option value="org_std_group">校级组织</a-select-option>
                <a-select-option value="volunteer_team">志愿者队伍</a-select-option>
              </a-select>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-input v-model="queryParam.name" placeholder="输入部门名称" />
            </a-col>
          </template>

          <a-col :md="6" :sm="24">
            <a-button @click.native="search">查询</a-button>
          </a-col>
        </a-row>
      </a-form>
      <a-card :loading="loading">
        <a-row type="flex" align="top">
          <!--组织机构-->
          <a-col flex="2" style="max-height:300px;overflow: auto;" v-if="searchType == 'deptInRole'">
            <div style="padding:0 10px;">
              <a-input-search
                @search="onSearchDepart"
                style="width:100%;margin-top: 10px"
                placeholder="请输入部门名称"
              />
            </div>
            <a-tree
              showLine
              :dropdownStyle="{ maxHeight: '200px', overflow: 'hidden' }"
              :treeData="departTree"
              :autoExpandParent="false"
              :expandedKeys="iExpandedKeys"
              :selectKeys="selectedDepartKeys"
              selectable
              @select="onSelectDepart"
              @expand="onExpand"
            />
          </a-col>
          <a-col flex="3">
            <a-tree
              v-if="searchType == 'dept'"
              showLine
              checkable
              multiple
              :selectable="false"
              :checkedKeys="selectedRowKeys"
              :treeData="dataSource"
              :expandedKeys="iExpandedKeys"
              @expand="onExpand"
              @check="onCheck"
            />
            <a-table
              v-else
              ref="table"
              size="middle"
              rowKey="id"
              :columns="columns"
              :dataSource="dataSource"
              :pagination="ipagination"
              :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
              :loading="loadingData"
              @change="handleTableChange"
            >
            </a-table>
          </a-col>
        </a-row>
      </a-card>
    </a-modal>
  </div>
</template>

<script>
import { filterObj } from '@/utils/util'
import { postAction, getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { queryMyDepartTreeList, searchByKeywords } from '@/api/api'
import { filter } from 'lodash'
let columnsMap = {
  user: [
    {
      title: '学工号',
      align: 'center',
      dataIndex: 'username'
    },
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'realname'
    },
    {
      title: '学院',
      align: 'center',
      dataIndex: 'college'
    },
    {
      title: '专业',
      align: 'center',
      dataIndex: 'major'
    },
    {
      title: '年级',
      align: 'center',
      dataIndex: 'grade'
    },
    {
      title: '班级',
      align: 'center',
      dataIndex: 'clazz'
    }
  ],
  role: [
    {
      title: '角色名称',
      align: 'center',
      dataIndex: 'roleName',
      width: 120
    },
    {
      title: '角色编码',
      align: 'center',
      dataIndex: 'roleCode'
    }
  ],
  dept: [
    {
      title: '部门名称',
      align: 'center',
      dataIndex: 'name',
      width: 120
    },
    {
      title: '部门编码',
      align: 'center',
      dataIndex: 'clazz'
    }
  ],
  deptInRole: [
    {
      title: '部门',
      align: 'center',
      dataIndex: 'departId_dictText',
      width: 120
    },
    {
      title: '部门角色',
      align: 'center',
      dataIndex: 'roleName'
    }
  ],
  post: [
    {
      title: '职务编码',
      align: 'center',
      dataIndex: 'code'
    },
    {
      title: '职务名称',
      align: 'center',
      dataIndex: 'name'
    },
    {
      title: '职级',
      align: 'center',
      dataIndex: 'postRank_dictText'
    }
  ],
  deptInPost: [
    {
      title: '部门类型',
      align: 'center',
      dataIndex: 'category_dictText'
    },
    {
      title: '职务编码',
      align: 'center',
      dataIndex: 'postCode'
    },
    {
      title: '职务名称',
      align: 'center',
      dataIndex: 'postName'
    },
    {
      title: '职级',
      align: 'center',
      dataIndex: 'postRank_dictText'
    }
  ]
}
let urlList = {
  user: '/sys/user/list',
  role: '/sys/role/list',
  dept: '/sys/sysDepart/queryTreeList',
  deptInRole: '/sys/sysDepartRole/list',
  post: '/sys/position/list',
  deptInPost: '/sys/userPosition/list'
}

export default {
  name: 'XSearchList',
  props: {
    value: [String, Number],
    disabled: Boolean,
    searchType: {
      type: String,
      default() {
        return 'user'
      }
    },
    searchIcon: Boolean,
    searchBtnText: String
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      loading: false,
      loadingData: false,
      visible: false,
      modalWidth: 800,
      names: '',
      departTree: [],
      queryParam: {},
      dataSource: [],
      selectedDepartKeys: [],
      iExpandedKeys: [],
      selectedRowKeys: [],
      selectedIds: '',
      title: '用户',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      }
    }
  },
  computed: {
    columns() {
      return columnsMap[this.searchType || 'user']
    },
    url() {
      return urlList[this.searchType || 'user']
    },
    selectDataRows() {
      let that = this
      let values = []
      function findSelected (list){
        filter(list, function(item) {
          if(that.selectedRowKeys.includes(item.id)){
            values.push(item)
          }
          if(Array.isArray(item.children)){
            findSelected(item.children)
          }
        })
      }
      findSelected(that.dataSource)
      return values
    }
  },
  watch: {
    value:{
      handler(nv, ov) {
        if (nv) {
          this.selectedIds = nv
          this.selectedRowKeys = nv.split(',')||[]
          this.onSearch()
        } else {
          this.dataSource = []
        }
      },
      immediate:true
    },
    searchType(nv, ov) {
      if (nv && nv != ov) {
        this.clear()
      }
    }
  },
  methods: {
    clear() {
      this.names = ''
      this.queryParam = {}
      this.dataSource = []
      this.checkedKeys = []
      this.selectedDepartKeys = []
      this.iExpandedKeys = []
      this.selectedRowKeys = []
      this.selectedIds = ''
    },
    handleSelected() {
      this.setValues()
      this.$emit('input', this.selectedIds)
      this.$emit('change', this.selectedIds)
      this.$emit('onselect', {names:this.names,values:this.selectedIds,item:this.selectDataRows})
      this.visible = false
    },
    setValues(){
      let data = this.selectDataRows.map(item => {
        let name = item.realname
        if(this.searchType == 'role') name = item.roleName
        if(this.searchType == 'deptInRole') name = item.roleName
        if(this.searchType == 'deptInPost') name = item.postName
        if(this.searchType == 'dept') name = item.departName
        return { id: item.id, name: name }
      })
      let ids = data.map(item => {
        return item.id
      })
      let names = data.map(item => {
        return item.name
      })
      this.names = names.join(',')
      this.selectedIds = ids.join(',')
    },
    close() {
      this.visible = false
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    onSelectDepart(selectedKeys, e) {
      if (this.selectedDepartKeys[0] !== selectedKeys[0]) {
        this.selectedDepartKeys = [selectedKeys[0]]
      }
      let record = e.node.dataRef
      this.queryParam.deptId = record.id
      this.loadData(1)
    },
    onCheck(checkedKeys, info) {
      this.hiding = false
      //this.checkedKeys = checkedKeys.checked
      // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
      if (this.checkStrictly) {
        this.selectedRowKeys = checkedKeys.checked
      } else {
        this.selectedRowKeys = checkedKeys
      }
      // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
    },
    onExpand(expandedKeys) {
      this.iExpandedKeys = expandedKeys
      // this.autoExpandParent = false
    },
    search() {
      let url = '/sys/sysDepart/searchBy'
      let that = this
      if (this.searchType == 'dept' && this.queryParam.keyWord) {
        getAction(url, { keyWord: this.queryParam.keyWord }).then(res => {
          if (res.success) {
            that.dataSource = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.dataSource.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        this.onSearch()
      }
    },
    // 设置树节点展开
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    // 表格选中
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onSearch() {
      if (this.searchType === 'deptInRole') this.loadTree()
      this.loadData(1)
    },
    onSearchDepart(value) {
      let that = this
      if (value) {
        searchByKeywords({ keyWord: value, myDeptSearch: '1' }).then(res => {
          if (res.success) {
            that.departTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.departTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    // 加载部门树
    loadTree() {
      var that = this
      that.departTree = []
      queryMyDepartTreeList({}).then(res => {
        if (res.success && res.result) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.departTree.push(temp)
            that.setThisExpandedKeys(temp)
          }
          this.loading = false
        }
      })
    },
    async loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loadingData = true
      let params = this.getQueryParams() //查询条件
      await getAction(this.url, params)
        .then(res => {
          if (res.success) {
            this.dataSource = []
            if (this.searchType == 'dept') {
              //部门全选后，再添加部门，选中数量增多
              for (let i = 0; i < res.result.length; i++) {
                let temp = res.result[i]
                this.dataSource.push(temp)
                this.setThisExpandedKeys(temp)
              }
            } else {
              this.dataSource = res.result.records
              this.ipagination.total = res.result.total
            }
            this.setValues()
          }
        })
        .finally(() => {
          this.loadingData = false
        })
    },
    handleTableChange(pagination, filters, sorter) {
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    }
  }
}
</script>

<style scoped>
.userSearch {
}
</style>
